package com.stone.front.user.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.stone.back.user.entity.BfCountry;
import com.stone.back.user.entity.BfUser;
import com.stone.base.controller.BaseController;
import com.stone.common.util.MailClient;
import com.stone.common.util.Md5Util;
import com.stone.common.util.RandomUtil;
import com.stone.common.util.RandomValidateCodeUtil;
import com.stone.front.user.service.IUserFrontService;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 前台用户管理
 * @author Stone P
 *
 */
@Controller
@RequestMapping("/frontUserCtl")
public class UserFrontController extends BaseController {
	@Autowired
	private IUserFrontService userFrontService;
	
	/**
	 * 前台用户登录
	 * @param email			email
	 * @param password		密码
	 * @return
	 */
	@RequestMapping("/userLogin")
	public String userLogin(String email, String password, HttpServletResponse response, HttpSession session, RedirectAttributes redirect) {
                password = Md5Util.toMD5(password);
		BfUser user = this.userFrontService.userLogin(email, password);
		if(null != user){
			if(1 == user.getStatus()){
				session.setAttribute(this.FRONTUSER, user);
                return "/common/reload";
			} else {
                redirect.addFlashAttribute("message", "请先去邮箱该激活用户!");
                return "redirect:/frontUserCtl/toRegister";
			}
			//mv.addObject(this.CNINFO, "恭喜您\"" + user.getUsername() + "\"，登陆成功!");
			//mv.addObject(this.USINFO, "Congratulations on your successful landing of \"" + user.getUsername() + "\"");
		} else {
            redirect.addFlashAttribute("message", "登陆失败，用户名密码错误!");
            return "redirect:/frontUserCtl/toRegister";
			//mv.addObject(this.CNINFO, "登陆失败，用户名密码错误!");
			//mv.addObject(this.USINFO, "Login failed, the username or password error!");
		}
	}

	/**
	 * 前台用户注销
	 * @return
	 */
	@RequestMapping("/userLogout")
	public ModelAndView userLogout(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("redirect:/index");
		request.getSession().removeAttribute(this.FRONTUSER);
		return mv;
		
	}
	
	/**
	 * 验证email是否存在
	 * @param email		登录名
	 * @return
	 */
	@RequestMapping("/checkEmailName")
        public @ResponseBody String selectUserByEmail(String email, HttpServletRequest request) {
		int count = this.userFrontService.selectUserByEmail(email);
		return String.valueOf(count);
	}
	
	/**
	 * 查询国家列表
	 * @return
	 */
	@RequestMapping("/selectCountry")
    public @ResponseBody List<BfCountry> selectCountry(HttpServletRequest request) {
		List<BfCountry> list = new ArrayList<BfCountry>();
		ServletContext application = request.getSession().getServletContext();
		Object countryObj = application.getAttribute("countryList");
		if(null != countryObj) {
			list = (List<BfCountry>) countryObj;
		} else {
			list = this.userFrontService.selectCountry();
			application.setAttribute("countryList", list);
		}
		return list;
	}
	
	/**
	 * 去注册用户
	 * @return
	 */
	@RequestMapping("/toRegister")
    public ModelAndView toRegister(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/front/login");
		//防止重复提交
		String registerSubmitMark = RandomStringUtils.randomAlphanumeric(16);
		request.getSession().setAttribute(this.REGISTERSUBMITMARK, registerSubmitMark);
		return mv;
	}

	
	/**
	 * 验证码验证
	 * @param randomCode	验证码
	 * @return
	 */
	@RequestMapping("/checkRandomCode")
	public @ResponseBody String checkRandomCode(String randomCode, HttpServletRequest request) {
		String checkFlag = "0";
		Object securityCodeObj = request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
		if(null == securityCodeObj){
			checkFlag = "0";
		} else if(securityCodeObj.toString().toUpperCase().equals(randomCode.toUpperCase())) {
			checkFlag = "1";
		}
		return checkFlag;
	}
	
	/**
	 * 增加用户
	 * @param user	用户信息
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/register")
    public ModelAndView addUser(BfUser user, String submitMark, HttpServletRequest request) throws Exception {
		ModelAndView mv = new ModelAndView("/front/userinfo");
		Object registerSubmitMarkObj = request.getSession().getAttribute(this.REGISTERSUBMITMARK);
		if(null != registerSubmitMarkObj) {
			if(registerSubmitMarkObj.toString().equals(submitMark)) {
				try {
					//激活验证码
					String checkCode = RandomUtil.getRandom16();
					user.setCreatedate(new Date());
					user.setPassword(Md5Util.toMD5(user.getPassword()));
					user.setType(1);
					user.setCheckcode(Md5Util.toMD5(checkCode));
					user.setStatus(0);
                    if(user.getSex() == null)
                        user.setSex(1);
					this.userFrontService.addUser(user);
					request.getSession().removeAttribute(this.REGISTERSUBMITMARK);
//					request.getSession().setAttribute(this.FRONTUSER, user);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		MailClient mailClient = new MailClient();
    	String uri = request.getRequestURI();
    	String host = request.getRemoteHost();
    	int port = request.getLocalPort();
    	uri = uri.substring(0, uri.lastIndexOf("/")) + "/activateUser?checkCode=";
    	String url = "http://" + host + ":" + port + uri;
		mailClient.setStrBufferCon("谢谢您注册BreakingFast！ \n 请点击下面链接进行账户激活 \n " + url);
		boolean sendStatus = mailClient.sendMail(user.getEmail(), user.getCheckcode());
		if(sendStatus) {
			mv.addObject("cninfo", "注册成功!请去邮箱激活账号！");
			mv.addObject("usinfo", "Registration is successful！Please go to the mailbox account activation！");
			mv.addObject("message", "恭喜你注册成功了,请去注册邮箱激活账户，请关闭窗口并刷新页面");
		} else {
		mv.addObject("message", "对不起激活邮件发送失败！请检查注册邮箱或者联系我们！");
		}
		return mv;
	}
	
	/**
	 * 激活用户
	 * @return
	 */
	@RequestMapping("/activateUser")
	public ModelAndView activateUser(String checkCode, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/front/info");
		Integer userId = this.userFrontService.selectUserByCheckCode(checkCode);
		if(null != userId) {
			BfUser user = this.userFrontService.selectUserDetail(userId);
			user.setStatus(1);
			this.userFrontService.updateUser(user);
			mv.addObject("cninfo", "恭喜您 " + user.getEmail() + " ，激活成功！");
			mv.addObject("usinfo", "Congratulations " + user.getEmail() + " ！successfully activated！");
		} else {
			mv.addObject("cninfo", "对不起链接无效！");
			mv.addObject("usinfo", "Sorry the link is invalid！");
		}
		return mv;
	}
	
	/**
	 * 修改用户
	 * @param user	用户信息
	 * @return
	 */
	@RequestMapping("/update")
    public ModelAndView updateUser(BfUser user, String submitMark, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/front/userinfo");
		try {
			user.setPassword(Md5Util.toMD5(user.getPassword()));
			this.userFrontService.updateUser(user);
			request.getSession().setAttribute(this.FRONTUSER, user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	/**
	 * 查询用户详情
	 * @param userId	用户Id
	 * @return
	 */
	@RequestMapping("/detail")
    public ModelAndView selectUserDetail(int userId, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("/front/user/userdetail");
		BfUser user = this.userFrontService.selectUserDetail(userId);
		mv.addObject("user", user);
		return mv;
	}
        
    /**
     * 我的BF
     * @return 
     */
    @RequestMapping(value = "/myaccount", method = RequestMethod.GET)
    public String toMyAccount() {
        return "/front/myaccount";
    }
    
    /**
     * 查询当前用户信息
     * @param request
     * @return 
     */
    @RequestMapping(value = "/api/user", method = RequestMethod.GET)
    public @ResponseBody BfUser queryCurrentUser(HttpServletRequest request) {
        return this.getFrontCurrentUser(request);
    }
    
    /**
     * 更新当前用户信息
     * @param request
     * @return 
     */
    @RequestMapping(value = "/api/user", method = RequestMethod.POST)
    public HttpEntity<String> updateCurrentUser(@RequestBody BfUser in, HttpServletRequest request) {
        BfUser current = this.getFrontCurrentUser(request);
        if(current == null)
            return new ResponseEntity("未登录", HttpStatus.METHOD_FAILURE);
        
        // 当前用户和将要更新数据的用户是否一致
        if(!current.getUserid().equals(in.getUserid()))
            throw new UnsupportedOperationException();
        
        // 只有旧密码输入正确才能进行用户信息的修改操作
        if(!current.getPassword().equals(Md5Util.toMD5(in.getOldpassword())))
            return new ResponseEntity("请准确输入旧密码", HttpStatus.METHOD_FAILURE);
                    
        // 保存用户修改信息
        in.setPassword(Md5Util.toMD5(in.getPassword()));
        BfUser user = userFrontService.updateUser(in.getUserid(), in.getUsername(), in.getEmail(), in.getPassword(), in.getBirthday(), in.getSex(), in.getAddress());
        
        // 保证Session和数据库一致性
        if(user == null)
            user = current;
        this.setFrontCurrentUser(user, request);
        
        return new ResponseEntity(HttpStatus.OK);
    }
        
    public static void main(String[] args) {
    	String host = "http://localhost:8080/BreakingFast/frontUserCtl/register";
    	String url = host.substring(0, host.lastIndexOf("/"));
    	System.out.println(url);
	}
        
}
